# 音乐网站
from web.Script.ScriptTools import Request
import requests


class Script_2t58_com:
    def __init__(self):
        self._domain = 'http://www.2t58.com'
        self.YyRequest = Request.RequestTools()

    # 公共函数: 获取名称、封面、链接
    def _get_pic_item(self, lis):
        responses = []
        for obj in lis:
            responses.append({
                "name": obj.xpath('./div[2]/a/text()')[0],
                "link": self._domain + obj.xpath('./div[2]/a/@href')[0],
                "img": obj.xpath('./div[1]/a/img/@src')[0]
            })

        return responses

    # 公共函数: 获取歌曲名称、链接、mv
    def _get_music_item(self, lis):
        responses = []
        for obj in lis:
            if len(obj.xpath('./div')) < 2:
                responses.append({
                    "name": obj.xpath('./div[1]/a/text()')[0],
                    "link": self._domain + obj.xpath('./div[1]/a/@href')[0],
                    "mv": None
                })
            else:
                responses.append({
                    "name": ''.join(obj.xpath('./div[1]/a/text()')[0].split()),
                    "link": self._domain + obj.xpath('./div[1]/a/@href')[0],
                    "mv": self._domain + obj.xpath('./div[2]/a/@href')[0]
                })
        return responses

    # 公共函数: 获取分页
    def _get_page(self, etree_str):
        def get_temp(path):
            parts = path.rsplit('/', 1)  # 从右向左分割一次，保留最后一个 '/' 之前的所有内容
            if parts:
                # 如果parts不为空，即路径中有 '/'
                new_path = '/'.join(parts[:-1])  # 移除最后一部分（即文件名及其前面的部分）
                if parts[-1].endswith('.html'):
                    # 如果最后一部分以 '.html' 结尾，你可能想进一步处理它
                    # 但在这个例子中，我们只是想移除它，所以上面的操作已经足够
                    return new_path
            else:
                # 如果没有 '/'，则路径可能只是文件名，直接返回空字符串或原始路径
                return path

        page_list = etree_str.xpath('//*[@class="page"]/a')
        page_obj = {"this_page": None, "next_page": None, "link_template": None}
        for obj in page_list:
            if len(obj.xpath('./@class')) > 0:

                if obj.xpath('./@class')[0] == 'current':
                    page_obj['this_page'] = obj.xpath('./text()')[0]
                elif obj.xpath('./@class')[0] == 'lkpc':
                    page_obj['next_page'] = str(obj.xpath('./@href')[0]).split('/')[-1].split('.')[0]
                    page_obj['link_template'] = self._domain + get_temp(obj.xpath('./@href')[0]) + '/'
            else:
                if obj.xpath('./text()')[0] == '尾页':
                    page_obj['next_page'] = str(obj.xpath('./@href')[0]).split('/')[-1].split('.')[0]
                    page_obj['link_template'] = self._domain + get_temp(obj.xpath('./@href')[0]) + '/'
        return page_obj

    # 获取歌手热门歌曲
    def get_actor_hot_music(self, link):
        etree_str = self.YyRequest.get_html_tree(self.YyRequest.get_html(url = link))
        # 歌手名
        name = etree_str.xpath('//*[@class="singer_info"]/div[2]/h1/text()')[0]
        # 歌手简介
        actor_info = etree_str.xpath('//*[@class="singer_info"]/div[2]/div/p/text() | //*[@class="singer_info"]/div[2]/div/text()')[0]
        if actor_info == " ":
            actor_info = etree_str.xpath('//*[@class="singer_info"]/div[2]/div/p/text()')[0]
        # 获取最新歌曲
        new_music = self._get_music_item(etree_str.xpath('//*[@class="play_list"]/ul/li'))
        # 分页
        page = self._get_page(etree_str)
        return {
            "name": name,
            "actor_info": actor_info,
            "new_music": new_music,
            "page": page
        }

    # 获取：热门歌手、热门歌单、热门视频、热门歌曲
    def get_hot(self):
        etree_str = self.YyRequest.get_html_tree(self.YyRequest.get_html(url = self._domain))
        # 热门歌手
        hot_actors = self._get_pic_item(etree_str.xpath('//*[@class="lksinger_list"]/ul/li'))
        # 热门歌单
        hot_song_list = self._get_pic_item(etree_str.xpath('//*[@class="ilingku_list"]')[0].xpath('./ul/li'))
        # 热门视频
        hot_video_list = self._get_pic_item(etree_str.xpath('//*[@class="ilingku_list"]')[1].xpath('./ul/li'))
        # 热门歌曲
        hot_music = self._get_music_item(etree_str.xpath('//*[@class="ilingkuplay_list"]/ul/li'))

        return {
            "hot_actors": {
                "name": "热门歌手",
                "data": hot_actors
            },
            "hot_song_list": {
                "name": "热门歌单",
                "data": hot_song_list
            },
            "hot_video_list": {
                "name": "热门视频",
                "data": hot_video_list
            },
            "hot_music": {
                "name": "热门歌曲",
                "data": hot_music
            }
        }

    # 筛选分类
    def _get_types_theme(self, etree_str):
        # 获取分类

        types_list = []
        for obj in etree_str.xpath('//*[@class="ilingku_fl"]'):
            a = []
            c = obj.xpath('./li')[0:1][0].xpath('./text()')[0]
            for divs in obj.xpath('./li')[1::]:
                b = {'name': divs.xpath('./a/text()')[0], 'link': self._domain + divs.xpath('./a/@href')[0]}
                a.append(b)
            types_list.append({
                "name": c,
                "data": a,
            })
        return types_list

    # 获取更新时间
    def _get_update_time(self, etree_str):
        update_time = etree_str.xpath('//*[@class="pagedata"]/span/text()')[0]
        return update_time

    # 根据音乐链接获取歌曲
    def get_music_link(self, link):
        etree_str = self.YyRequest.get_html_tree(self.YyRequest.get_html(url = link))
        # 获取音乐信息
        headers = {
            'Referer': link,
        }
        data = {
            'id': link.split('/')[-1].replace('.html', ''),
            'type': 'music',
        }
        response = self.YyRequest.request_post(url = self._domain + '/js/play.php', data = data, headers = headers)
        # 字幕
        lyric = requests.get(url = f'http://api.eev3.com/lc.php?cid={response["lkid"]}').json()
        lyric['lrc'] = lyric['lrc'].replace('歌词由 www.wxmp3.com', '歌词由 Yy云爬虫工具')
        response['lyric'] = lyric

        # 获取歌手信息
        max_music = etree_str.xpath('//*[@id="num"]/text()')[0]
        athor_link = etree_str.xpath('//*[@class="name"]/a/@href')[0]
        athor_name = etree_str.xpath('//*[@class="name"]/a/text()')[0]
        response['actor'] = {
            "name": athor_name,
            "link": self._domain + athor_link,
            "max_music": max_music
        }
        return response

    # 根据视频链接获取视频
    def get_video_link(self, link):
        etree_str = self.YyRequest.get_html_tree(self.YyRequest.get_html(url = link))
        # 获取视频信息
        headers = {
            'Referer': link,
        }
        response = requests.head(
            url = self._domain + f'/plug/down.php?ac=vplay&id={link.split('/')[-1].replace('.html', '')}&q=3000',
            headers = headers).headers['Location']

        athor_name = etree_str.xpath('//*[@class="name"]/a/text()')[0]
        athor_link = self._domain + etree_str.xpath('//*[@class="name"]/a/@href')[0]
        max_music = etree_str.xpath('//*[@id="num"]/text()')[0]

        return {
            "video_link": response,
            "video_name": etree_str.xpath('//*[@class="play_left"]/div[1]/h1/text()')[0],
            "athor": {
                "name": athor_name,
                "link": athor_link,
                "max_music": max_music
            }
        }

    # 搜索音乐
    def search_music(self, keyword):
        etree_str = self.YyRequest.get_html_tree(self.YyRequest.get_html(url = self._domain + f'/so/{keyword}.html'))
        music_list = self._get_music_item(etree_str.xpath('//*[@class="play_list"]/ul/li'))
        page = self._get_page(etree_str)
        max_music = etree_str.xpath('//*[@class="pagedata"]/span/text()')[0]
        return {
            "music_list": music_list,
            "page": page,
            "max_music": max_music
        }

    # 新歌榜、TOP榜单、DJ舞曲
    def get_music_rank(self, types = 'new'):
        """
        types: new(新歌榜)、top(TOP榜)、djwuqu(DJ舞曲)
        """
        url = self._domain + f'/list/{types}.html'
        etree_str = self.YyRequest.get_html_tree(self.YyRequest.get_html(url = url))
        # 获取榜单分类
        rank_list = []
        for obj in etree_str.xpath('//*[@class="ilingku_fl"]/li'):
            rank_list.append({
                "name": obj.xpath('./a/text()')[0],
                "link": str(obj.xpath('./a/@href')[0]).split('/')[-1].replace('.html', '')
            })
        # 获取音乐数据
        music_list = self._get_music_item(etree_str.xpath('//*[@class="play_list"]/ul/li'))
        # 获取更新时间
        update_time = etree_str.xpath('//*[@class="pagedata"]/span/text()')[0]
        # 获取分页
        page = self._get_page(etree_str)
        return {
            "rank_list": rank_list,
            "music_list": music_list,
            "page": page,
            "update_time": update_time
        }

    # 筛选歌手
    def get_actor(self, types = 'index', sex = 'index', clas = 'index', As = 'index', pages = 1):
        """
        types: 歌手分类,
        sex: 性别,
        clas: 歌手类型,
        As: 字母排序(可选值: a-z小写)
        """
        url = self._domain + f'/singerlist/{types}/{sex}/{clas}/{As}/{pages}.html'
        etree_str = self.YyRequest.get_html_tree(self.YyRequest.get_html(url = url))

        types_list = self._get_types_theme(etree_str)

        # 获取歌手列表
        actor_list = self._get_pic_item(lis = etree_str.xpath('//*[@class="singer_list"]/ul/li'))

        # 分页
        page = self._get_page(etree_str)
        max_music = self._get_update_time(etree_str)
        return {
            "types_list": types_list,
            "actor_list": actor_list,
            "page": page,
            "max_music": max_music,
        }

    # 筛选歌单
    def get_songe_music_list(self, types = 'index', pages = 1):
        """
        types: 歌单分类,
        """
        url = self._domain + f'/playtype/{types}/{pages}.html'
        etree_str = self.YyRequest.get_html_tree(self.YyRequest.get_html(url = url))

        types_list = self._get_types_theme(etree_str)

        # 获取歌手列表
        actor_list = self._get_pic_item(lis = etree_str.xpath('//*[@class="video_list"]/ul/li'))

        # 分页
        page = self._get_page(etree_str)
        max_music = self._get_update_time(etree_str)
        return {
            "types_list": types_list,
            "actor_list": actor_list,
            "page": page,
            "max_music": max_music,
        }

    # 筛选电台
    def get_radio(self, types = 'index', pages = 1):

        """
        types: 歌单分类,
        """
        url = self._domain + f'/radiolist/{types}/{pages}.html'
        etree_str = self.YyRequest.get_html_tree(self.YyRequest.get_html(url = url))

        types_list = self._get_types_theme(etree_str)

        # 获取歌手列表
        actor_list = self._get_pic_item(lis = etree_str.xpath('//*[@class="video_list"]/ul/li'))

        # 分页
        page = self._get_page(etree_str)
        max_music = self._get_update_time(etree_str)
        return {
            "types_list": types_list,
            "actor_list": actor_list,
            "page": page,
            "max_music": max_music,
        }

    # 筛选高清MV
    def get_hd_mv(self, types = "index", pages = 1):
        """
        types: 歌单分类,
        """
        url = self._domain + f'/mvlist/{types}/{pages}.html'
        etree_str = self.YyRequest.get_html_tree(self.YyRequest.get_html(url = url))

        types_list = self._get_types_theme(etree_str)

        # 获取歌手列表
        actor_list = self._get_pic_item(lis = etree_str.xpath('//*[@class="video_list"]/ul/li'))

        # 分页
        page = self._get_page(etree_str)
        max_music = self._get_update_time(etree_str)
        return {
            "types_list": types_list,
            "actor_list": actor_list,
            "page": page,
            "max_music": max_music,
        }


if __name__ == '__main__':
    scripts = Script_2t58_com()
    print(scripts.get_hd_mv(pages = 1))
